<?php

namespace App\Http\Resources\OpenShop\InvestmentPromotion;

use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopProcessDetailModel;
use App\Service\OpenShop\User\RmsUserService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Database\Eloquent\HigherOrderBuilderProxy;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;

class ProcessDetailResource extends JsonResource
{

    public static ?Collection $rmsUser = null;

    /**
     * Transform the resource into an array.
     *
     * @param Request $request
     * @return array
     */
    public function toArray($request): array
    {
        return [
            'mainProcessDesc' => $this->mainProcessDesc,
            'processDesc'     => $this->processDesc,
            'status'          => $this->status,
            'createdAt'       => formatDate($this->createdAt->timestamp),
            'createdUserName' => $this->getCreateUserName()
        ];
    }


    /**
     * 获取流程操作人
     *
     * @return HigherOrderBuilderProxy|mixed|string
     * @throws GuzzleException
     */
    public function getCreateUserName(): string
    {
        if (
                (
                    $this->mainProcessType == MainProcessEnum::MAIN_PROCESS_INVESTMENT_SIGN
                    &&
                    in_array($this->processType,
                        array(MainProcessEnum::INVESTMENT_SIGN_CONTRACT_PAID, MainProcessEnum::INVESTMENT_SIGN_CONTRACT_SIGNED))
                )
                ||
                (
                    $this->mainProcessType == MainProcessEnum::MAIN_PROCESS_SHOP_LOCATION
                    &&
                    in_array($this->processType, array(MainProcessEnum::SHOP_LOCATION_CONFIRM))
                )
        ) {
            $mainProcessInfo  = OpenShopMainProcessModel::query()->with("signOrderRel.identityCardRel")
                                                        ->where("id", $this->mainProcessId)->first();
            return  $mainProcessInfo->signOrderRel->identityCardRel->name ?? '';
        } else {
            $userInfo         = empty($this->createdByUid) || empty(self::$rmsUser) || ! self::$rmsUser->offsetExists($this->createdByUid) ?
                null : self::$rmsUser->get($this->createdByUid);
            return $userInfo ? $userInfo['username'] : '';
        }
    }
}
